package com.nb.changecolortext;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private LinearLayout mTabs;
    private ViewPager2 mViewPager;
    private String items[] = {"直播", "推荐", "热门", "影视", "图片"};
    private List<ChangeColorText> mIndicators;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initTabs();
        initViewPager();
    }

    private void initViewPager() {
        mViewPager = findViewById(R.id.view_pager);
        mViewPager.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return ItemFragment.newInstance(items[position]);
            }

            @Override
            public int getItemCount() {
                return items.length;
            }
        });

        mViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                ChangeColorText left = mIndicators.get(position);
                left.setDirection(ChangeColorText.Direction.RIGHT_TO_LEFT);
                left.setProcess(1 - positionOffset);

                if (position == mIndicators.size() - 1) {
                    return;
                }
                ChangeColorText right = mIndicators.get(position + 1);
                right.setDirection(ChangeColorText.Direction.LEFT_TO_RIGHT);
                right.setProcess(positionOffset);
            }
        });
    }

    private void initTabs() {
        mIndicators = new ArrayList<>();
        mTabs = findViewById(R.id.ll_tab);
        for (int i = 0; i < items.length; i++) {
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.weight = 1;
            ChangeColorText text = new ChangeColorText(this);
            text.setLayoutParams(layoutParams);
            text.setText(items[i]);
            text.setTextSize(20);
            text.setDefaultColor(Color.GRAY);
            text.setChangeColor(Color.RED);
            mIndicators.add(text);
            mTabs.addView(text);


        }

    }
}